<?php
###############   COPYLEFT GPLv3 LICENSE   ###############
##
## JFX Version 0.2.7
## Website Management Software
## www.jfxcms.com
##
## Copyright 2009 GPLv3 - http://www.opensource.org/licenses/gpl-3.0.html
##
## Anthony Gallon
## oi_antz@hotmail.com
##
## Permission is hereby granted to any person having a copy of this software
## to freely use and modify as required so long as the copyright notices
## and branding remain intact.
##
## Full license details available at http://www.jfxcms.com/license
##
###############   COPYLEFT GPLv3 LICENSE   ###############

JFX::checkAdminPermsRedirect('core', 'perm_manage_domains');

$THEME->addBreadcrumb($this->adminUrl.'/domains/', $this->lang('ap_title_domains'));

if(Antz_IntelliForm::submitted('root-page') || (get('root-page')==1 && get('domain')!='')){
    // wanting to set the new root page
    if(get('page')!=''){
        // have selected the new page
        $domainid = (int) get('domain');
        $newdomainid = (int) get('page');
        if($DB->countRows($CONFIG->dbprefix.'pages', "id = {$domainid}")==0){
            JFX::addError('Invalid domain selected');
            JFX::redirect($CONFIG->adminUrl.'/domains');
        }
        if($DB->countRows($CONFIG->dbprefix.'pages', "id = {$newdomainid}")==0){
            JFX::addError('Invalid page selected');
            JFX::redirect($CONFIG->adminUrl.'/domains');
        }
        $existingDomain = $DB->oneValue($CONFIG->dbprefix.'pages', 'id', "parent_id = 0 AND domain_id = '{$domainid}'");
        $DB->update($CONFIG->dbprefix.'pages', array('parent_id' => $newdomainid), "id = '{$existingDomain}'");
        $DB->update($CONFIG->dbprefix.'pages', array('parent_id' => 0, 'domain_id' => $domainid), "id = '{$newdomainid}'");
        JFX::addSuccess('Your domain has been reassigned');
        JFX::redirect($CONFIG->adminUrl.'/domains');
    }else{
        // have to select the new page
        $pagesRecursive = JFX::getPageTree(0, $USER->workspace);
        $tree = '<ul id="jfxcore-domains-page-tree">'.JFX_Domains_MakeTree($pagesRecursive, post('domain')).'</ul>';

        $js = '
        $(document).ready(function(){
            $("#jfxcore-domains-page-tree").treeview({
                persist: "location",
                collapsed: true,
                unique: true
            });
        });
        ';

        $VIEW->addJs($js);

        echo '<h1>Setting new root page for domain</h1>';
        echo '<p>Note, the page selected here will be moved to root level and will become a domain. The existing domain (if any) will become
a sub-page of the selected page.</p>';

        echo $tree;
        return;
    }
}





if(Antz_IntelliForm::submitted('new-domain')){
    $dbParams = array(
        'domain_name' => post('domain'),
        'is_active' => 1
    );
    $DB->insert($CONFIG->dbprefix.'domains', $dbParams);
    JFX::addSuccess('Domain created!');
    JFX::redirect(THIS_PAGE_URL);
}




if(Antz_IntelliForm::submitted('delete-domain')){
    $id = (int) post('domain');

    if($DB->countRows($CONFIG->dbprefix.'domains', '1=1')==1){
        JFX::addError('You cannot delete the only domain in the system, the website would no longer work!');
        return;
    }

    if(post('confirm')!='1'){
        $formFields = array(
            array(
                'type' => 'hidden',
                'name' => 'domain',
                'value' => $id
            ),
            array(
                'type' => 'hidden',
                'name' => 'confirm',
                'value' => 1
            ),
            array(
                'type' => 'submit',
                'name' => 'submitBtn',
                'value' => 'Confirm Delete'
            )
        );

        $form = JFX::makeRapidForm($formFields, 'Confirm deletion of '.$DB->oneValue($CONFIG->dbprefix.'domains', 'domain_name', "id = '{$id}'"), 'delete-domain');
        echo '<h1>Confirm delete</h1>';
        echo '<p>This will delete all pages and blocks associated to this domain!</p>';
        echo $form->render();
        return;
    }else{
        // ready to delete
        $pageid = $DB->oneValue($CONFIG->dbprefix.'pages', 'id', "is_domain = 1 AND domain_id = '{$id}'");
        $DB->delete($CONFIG->dbprefix.'blocks', "page_id = {$pageid}");
        $DB->delete($CONFIG->dbprefix.'pages', 'id = '.$pageid);
        $DB->delete($CONFIG->dbprefix.'domains', 'id = '.$id);
        JFX::addSuccess('Domain deleted!');
        JFX::redirect(THIS_PAGE_URL);
    }
}


if(Antz_IntelliForm::submitted('default-domain')){
    $id = (int) post('domain');

    if($DB->countRows($CONFIG->dbprefix.'domains', "id = '{$id}'")==0){
        JFX::addError('Invalid domain to set default!');
        return;
    }

    $DB->query("UPDATE {$CONFIG->dbprefix}domains SET is_default = 0");
    $DB->update($CONFIG->dbprefix.'domains', array('is_default'=>1), "id = '{$id}'");

    JFX::addSuccess('Domain set to default!');
    JFX::redirect(THIS_PAGE_URL);

}









$domains = $DB->fetchAll("SELECT * FROM {$CONFIG->dbprefix}domains ORDER BY domain_name ASC");
$domainOpts = array();
foreach($domains as $k=>$v){
    $domainOpts[$v['id']] = $v['domain_name'];
};





$newFormFields = array(
    array(
        'name' => 'domain',
        'type' => 'text',
        'value' => post('domain'),
        'label' => 'Domain'
    ),
    array(
        'type' => 'checkbox',
        'name' => 'default',
        'value' => 1,
        'checked' => post('default'),
        'label' => 'Is default domain?'
    ),
    array(
        'name' => 'submitBtn',
        'type' => 'submit',
        'value' => 'Add Domain',
        'label' => '&nbsp;'
    )
);

$newForm = JFX::makeRapidForm($newFormFields, 'Create new domain', 'new-domain');



$deleteFormfields = array(
    array(
        'name' => 'domain',
        'type' => 'select',
        'label' => 'Domain',
        'options' => $domainOpts,
        'value' => post('domain')
    ),
    array(
        'name' => 'submitBtn',
        'type' => 'submit',
        'value' => 'Delete Domain',
        'label' => '&nbsp;'
    )
);

$deleteForm = JFX::makeRapidForm($deleteFormfields, 'Delete a Domain', 'delete-domain');





$defaultFormFields = array(
    array(
        'name' => 'domain',
        'type' => 'select',
        'label' => 'Domain',
        'options' => $domainOpts,
        'value' => post('domain', $CONFIG->domainid)
    ),
    array(
        'name' => 'submitBtn',
        'type' => 'submit',
        'value' => 'Make Default Domain',
        'label' => '&nbsp;'
    )
);

$defaultForm = JFX::makeRapidForm($defaultFormFields, 'Make a new Default Domain', 'default-domain');


$rootFormFields = array(
    array(
        'name' => 'domain',
        'value' => post('domain'),
        'options' => $domainOpts,
        'label' => 'Domain',
        'type' => 'select'
    ),
    array(
        'name' => 'submitBtn',
        'type' => 'submit',
        'value' => 'Select Root Page',
        'label' => '&nbsp;'
    )
);

$rootForm = JFX::makeRapidForm($rootFormFields, 'Select the root page', 'root-page');





echo '<div id="jfx-new-domain">'.$newForm->render().'</div>';
echo '<div id="jfx-delete-domain">'.$deleteForm->render().'</div>';
echo '<div id="jfx-default-domain">'.$defaultForm->render().'</div>';
echo '<div id="jfx-root-page">'.$rootForm->render().'</div>';

echo '<div class="jfx-clear"></div>';













function JFX_Domains_MakeTree($arr, $domain){
    $CONFIG = JFX::registry('config');
    $LANG = JFX::registry('lang');
    $returnString = '';
    foreach($arr as $k=>$v){

        if($v['parent_id']==0) $link = $LANG->getContent('core', 'page_title', $v['id']);
        else $link = '<a href="'.$CONFIG->adminUrl.'/domains?domain='.urlencode($domain).'&amp;root-page=1&amp;page='.$v['id'].'" id="page_'.$v['id'].'">'.$LANG->getContent('core', 'page_title', $v['id']).'</a>';
        
        if(isset($v['subpages']) && count($v['subpages'])>0){
            $subpages = '<ul>'.JFX_Domains_MakeTree($v['subpages'], $domain).'</ul>';
        }else{
            $subpages = '';
        }
        $returnString .= '<li>'.$link.$subpages.'</li>';
    }

    return $returnString;
}


